<template>
  <view class="wrap">
    <u--image
      width="180rpx"
      height="180rpx"
      :src="userInfo.pic"
      shape="circle"
      errorIcon="/static/images/loginPic.png"
      @click="uploadImg"
    ></u--image>
    <text class="tip">(注：头像大小不得超过200KB!)</text>
  </view>
</template>

<script>
import { baseUrl } from '@/config'
export default {
  data () {
    return {
      action: baseUrl + '/user/uploadImg'
    }
  },
  computed: {
    userInfo () {
      return this.$store.state.auth.userInfo
    }
  },
  methods: {
    uploadImg () {
      const this_ = this
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          const path = res.tempFilePaths
          const file = res.tempFiles
          uni.uploadFile({
            url: this_.action,
            filePath: path[0],
            name: 'file',
            formData: {
              'file': 'test'
            },
            success: (res) => {
              const { code, data } = JSON.parse(res.data)
              if (code === 200) {
                this_.userInfo.pic = `${baseUrl}/${data}`
                this_.$store.commit('setUserInfo', this_.userInfo)
                uni.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 2000
                })
              }
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrap {
  height: 300rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .tip {
    margin-top: 20rpx;
    font-size: 24rpx;
    color: rgb(144, 144, 144);
  }
}
</style>
